package com.wskj.ws.handler;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.wskj.system.mapper.SysUserMapper;
import com.wskj.ws.config.WebSocket;
import com.wskj.ws.config.WebSocketUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;

/**
 * 创建处理器 MyWebSocketHandler
 */
@Slf4j
public class MyWebSocketHandler implements WebSocketHandler {

    private static SysUserMapper sysUserMapper;

    /**
     * 依赖注入
     */
    static {
        sysUserMapper = SpringUtil.getBean(SysUserMapper.class);
    }

    // 建立新的 socket 连接后回调的方法
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从session中获取存放的参数
        String identifier = session.getAttributes().get("identifier")==null?"":String.valueOf(session.getAttributes().get("identifier"));
        WebSocket webSocket = new WebSocket();
        webSocket.setSession(session);
        webSocket.setIdentifier(identifier);
        WebSocketUser.getSessionMap().put(identifier,webSocket);
        log.info("有新的客户端链接：[{}],当前在线人数:[{}]", session.getId(), WebSocketUser.getSessionMap().size());
    }

    // 接收客户端发送的 Socket
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String userId = session.getAttributes().get("identifier")==null?"":String.valueOf(session.getAttributes().get("identifier"));
        // 连接发送的消息
        String msg = message.getPayload().toString();
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String toId = jsonObject.getString("toId");
        String msgInfo = jsonObject.getString("msgInfo");
        // 通过session向连接发送消息
        WebSocket webSocket = WebSocketUser.getSessionMap().get(toId);
        if(webSocket != null){
            WebSocketUser.sendMessageToUserByText(webSocket.getSession(),userId+"向你问好->"+msgInfo+"");
        } else {
            WebSocketUser.sendMessageToUserByText(session,"对方已离线");
        }
    }

    // 连接出错时，回调的方法
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("收到的错误信息：" + exception);
        String identifier = session.getAttributes().get("identifier")==null?"":String.valueOf(session.getAttributes().get("identifier"));
        WebSocketUser.removeUser(identifier);
    }

    // 连接关闭时，回调的方法
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        System.out.println("断开连接");
        String identifier = session.getAttributes().get("identifier")==null?"":String.valueOf(session.getAttributes().get("identifier"));
        WebSocketUser.removeUser(identifier);
    }


    // WebSocketHandler 是否处理部分消息 默认返回false即可
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
